<?php

namespace App\Admin\RowActions;

use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class CopyAction extends RowAction
{
    protected $model;

    public function __construct(string $model = null)
    {
        $this->model = $model;
    }

    /**
     * 标题
     *
     * @return string
     */
    public function title()
    {
        return '复制';
    }

    /**
     * 设置确认弹窗信息，如果返回空值，则不会弹出弹窗
     *
     * 允许返回字符串或数组类型
     *
     * @return array|string|void
     */
    public function confirm()
    {
        return [
            // 确认弹窗 title
            "您确定要复制这行数据吗？",
            // 确认弹窗 content
            $this->row->goods_name,
        ];
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return \Dcat\Admin\Actions\Response
     */
    public function handle(Request $request)
    {
        // 获取当前行ID
        $id = $this->getKey();

        $model = $request->get('model');

        // 复制数据
        $info = $model::find($id);
        $new_info = $info->replicate(['goods_name','barcode']);
        $new_info->goods_name = $info->goods_name."副本";
        $new_info->save();
//        dd($new_info);
        // 返回响应结果并刷新页面
        $miniProgram = \EasyWeChat::miniProgram(); // 小程序
        $response = $miniProgram->app_code->getUnlimit($new_info->getKey(),[
            "page"=>"pages/goodslist/selfgoodsinfo",
        ]);
        // 或
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $img_name = time().Str::random(3).".png";
            $filename = $response->saveAs(public_path().'/uploads/', $img_name);
            $new_info->update(['barcode'=>$filename]);
        }
        return $this->response()->success("复制成功[{$new_info->goods_name}]")->refresh();
    }

    /**
     * 设置要POST到接口的数据
     *
     * @return array
     */
    public function parameters()
    {
        return [
            // 把模型类名传递到接口
            'model' => $this->model,
        ];
    }
}
